<?php
declare (strict_types = 1);

namespace app\controller\admin;

use app\model\Role;
use app\model\User;
use tauthz\facade\Enforcer;
use think\facade\Validate;
use think\response\Json;

class AdminUser extends AdminBase
{

	protected $middleware = [
        'app\middleware\AdminLogin',
		'app\middleware\AdminAuth' => ['except' => ['role','personal','edit'] ]
	];

	private string $menuName = '用户管理';

    /**
     * 显示资源列表
     * @throws
     * @return Json
     */
    public function index():Json
    {
        $limit = input('pageSize/d',10);
        //分页配置
        $pageConfig = ['list_rows'=>$limit,'var_page'=>'pageNum'];

        //搜索字段配置
        $search = [
            [
                'label'=>'用户名称',//标签
                'prop'=> 'name',//表单名称
                'field' => 'username|nickname|email|mobile',//查询字段
                'placeholder'=> '模糊搜索账号|昵称|邮箱|手机',
                'required'=> false,//是否必填
                'expression' => 'like',//查询表达式：like,not like,in,not in,between,not between,null,not null,time,>,<,>=,<=,=,<>(!=),find(FIND_IN_SET)
                'type'=> 'input',//类型：input,select,date,datetime,year,month,week,datetimerange,daterange
                'typeof' => 's',//强制转换类型：d整数，a数组，s字符串，b布尔类型，f浮点数
            ],
        ];
        $map = [];
        $this->setMap($search,$map);

		$data = User::withoutField('password,delete_time')
            ->where($map)
            ->order('create_time','desc')
			->paginate($pageConfig)
            ->each(function($item){
                $item['password'] = '';
                if($item['status'] < 90){
                    $roles = Role::whereIn('id',$item['role_id'])->column('name');
                    $item['roles'] = count($roles) ? implode('，',$roles) : '';
                }else{
                    $item['roles'] = '超管';
                    $item['is_del'] = 1;
                    $item['is_edit'] = 1;
                }
                return $item;
            });

        $this->result['data'] = [
            'total' => $data->total(),
            'data' => $data->items(),
            'search' => $search
        ];

		return returnAdmin($this->request,$this->result,$this->menuName.'-列表',$this->adminInfo);
    }

    /**
     * 获取角色
     * @throws
     * @return Json
     */
    public function role():Json
    {
        $data = Role::field('id,name')
            ->where('status',1)
            ->order('sort','asc')
            ->select()
            ->each(function($item){
                $item['id'] = (string) $item['id'];
                return $item;
            })->toArray();

        $this->result['data'] = $data;
        return jJson($this->result);
    }

    /**
     * 获取个人信息
     * @throws
     * @return Json
     */
    public function personal():Json{
        $this->adminInfo['headimg'] = addDomain($this->adminInfo['headimg']);
        $this->result['data'] = $this->adminInfo;
        return jJson($this->result);
    }

    /**
     * 编辑个人信息
     * @throws
     * @return Json
     */
    public function edit():Json{
        try{
            //获取form表单
            $param = input('param.',[]);
            $param = toUnderline($param);

            $rule = [
                'nickname' => 'require|max:64',
                'mobile' => 'mobile',
                'email' => 'email',
                'password' => ['regex'=>'/[\w|\d|@|\.|\_]{6,16}/']
            ];

            $message = [
                'nickname.require' => '昵称必填',
                'nickname.max' => '昵称最多64个字符',
                'password.require' => '请输入登录密码',
                'password.regex' => '无效的密码格式',
                'mobile' => '手机号格式错误',
                'email' => 'EMAIL格式错误',
            ];
            $validate = Validate::rule($rule)->message($message);
            if(!$validate->check($param)){
                throw new \Exception($validate->getError());
            }

            $info = User::find($this->adminId);
            $save = [
                'nickname' => $param['nickname'],
                'mobile' => $param['mobile'],
                'email' => $param['email'],
            ];
            if($param['password']){
                $save['password'] = ph($param['password']);
                $save['last_login_time'] = time();
            }
            $avatar = $param['avatar'];
            if($info['headimg'] != $avatar){
                $save['headimg'] = removeDomain($avatar);
                //删除旧的图片文件
                if(is_file('.'.removeDomain($info['headimg']))){
                    @unlink('.'.removeDomain($info['headimg']));
                }
            }

            $info->save($save);

        }catch (\Exception $e){
            $this->result['code'] = 500;
            $this->result['msg'] = $e->getMessage();
        }
        return returnAdmin($this->request,$this->result,'个人资料-编辑',$this->adminInfo);
    }

    /**
	 * 保存编辑的资源
	 * @throws
	 * @return Json
	 */
	public function save():Json
	{
		//获取form表单
		$param = input('param.',[]);
		$param = toUnderline($param);

        $model = new User();
        $fields = $model->getFields();
        $pk = $model->getPk();
        $id = $param[$pk] ?? 0;
		try{
            $rule = [
                'username' => ['require','regex'=>'/^[\w|\d][\w|\d|@|\.|\_]{3,15}/'],
                'nickname' => 'require|max:64',
                'mobile' => 'mobile',
                'email' => 'email',
                'role_id' => 'array|min:1',
            ];
            if(!$id){
                $rule['password'] = ['require','regex'=>'/[\w|\d|@|\.|\_]{6,16}/'];
            }else{
                $rule['password'] = ['regex'=>'/[\w|\d|@|\.|\_]{6,16}/'];
            }
            $message = [
                'username.require' => '账户名称必填',
                'username.regex' => '账户名称格式错误',
                'username.unique' => '账户名称已存在，请重新输入',
                'nickname.require' => '昵称必填',
                'nickname.max' => '昵称最多64个字符',
                'password.require' => '请输入登录密码',
                'password.regex' => '无效的密码格式',
                'mobile' => '手机号格式错误',
                'email' => 'EMAIL格式错误',
                'role_id.array' => '请选择角色',
                'role_id.min' => '至少选择一个角色',
            ];
            $validate = Validate::rule($rule)->message($message);
            if(!$validate->check($param)){
                throw new \Exception($validate->getError());
            }
            if($param['password']){
                $param['password'] = ph($param['password']);
            }else{
                unset($param['password']);
            }
            $count = $model->where('id','<>',$id)->where('username',$param['username'])->count();
            if($count){
                throw new \Exception('账号已存在，请重新输入');
            }
			if(!$id){
				//新增
				$model->create($param,$fields);
			}else{
				//修改
				$info = $model->find($id);
				if(!$info){
					throw new \Exception('无效参数');
				}
                if($info['status'] > 90){
                    throw new \Exception('超管不能编辑，请登录个人中心修改');
                }
                unset($fields['username'],$fields['create_time']);
				$info->allowField($fields)->save($param);

                Enforcer::deleteRolesForUser($param['username']);
			}

            //获取权限菜单
            $roles = Role::field('id,alias')->whereIn('id',$param['role_id'])->select()->toArray();
            if(count($roles)){
                foreach ($roles as $r){
                    Enforcer::addRoleForUser($param['username'],'role_'.$r['alias']);
                }
            }

		}catch (\Exception $e){
			$this->result['code'] = 500;
			$this->result['msg'] = $e->getMessage();
		}
		return returnAdmin($this->request,$this->result,$this->menuName.'-编辑',$this->adminInfo);
	}



    /**
     * 删除指定资源
     * @throws
     * @return Json
     */
    public function delete():Json
    {

        $id = input('id/d',0);
        try{
            $user = User::find($id);
            if(!$user){
                throw new \Exception('无效参数');
            }
            if($user['status'] > 90){
                throw new \Exception('超管不能删除');
            }
            $img = $user->getData('headimg');
            $user->delete();
            if(is_file('.'.$img)){
                @unlink('.'.$img);
            }
            //删除所有角色
            Enforcer::deleteRolesForUser($user['username']);
            $this->result['msg'] = '删除ID：'.$id;
        }catch (\Exception $e){
            $this->result['code'] = 500;
            $this->result['msg'] = $e->getMessage();
        }

        return returnAdmin($this->request,$this->result,$this->menuName.'-删除',$this->adminInfo);
    }

}
